/*
  这里展示命名路由，在实际项目中使用得比较多
 */
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:swipeable_page_route/swipeable_page_route.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  final Map<String, Widget Function(BuildContext)> routerMap = {
    'other': (BuildContext context) => Other()
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        // 'other': (BuildContext context) => Other(),
        '/': (BuildContext context) => HomePage()
      },
      // home: HomePage() // 也可以把主页注册到路由表中
      onGenerateRoute: (RouteSettings settings) {
        // 通过路由钩子获取路由名，不在路由表中的才会回调
        // 所以我们将路由注册放到一个键值对里
        // 这样可以控制每个路由调用
        var routeName = settings.name;
        print('routeName=$routeName');

        // MaterialPageRoute 切换效果是上下滑动切换
        // return MaterialPageRoute(
        //     builder: routerMap[routeName],
        //     settings: settings);

        // CupertinoPageRoute 是IOS风格，左右切换
        // return CupertinoPageRoute(
        //     builder: routerMap[routeName] as Widget Function(BuildContext),
        //     settings: settings);

        // 通过左滑返回上一个界面的路由
        return SwipeablePageRoute(
            builder: routerMap[routeName] as Widget Function(BuildContext),
            settings: settings);

        // 我们还可以自定义路由，继承PageRoute，实现多种页面切换效果
      },

      navigatorObservers: [],
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("route"),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            // 跳转的时候传路由名称
            Navigator.pushNamed(context, 'other', arguments: 'Hi,Girl');
          }),
    );
  }
}

class Other extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //获取路由参数
    var args = ModalRoute.of(context)!.settings.arguments;
    print('args=$args');
    return Scaffold(
      appBar: AppBar(
        title: Text("other"),
      ),
      body: Center(
        child: Text(
          '$args',
          textDirection: TextDirection.ltr,
        ),
      ),
    );
  }
}
